# -*- coding: utf-8 -*-
import hashlib
import json
import logging
from collections import OrderedDict
from datetime import datetime

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)
_TRACKER = logging.getLogger('tracker')

_GATEWAY = 'https://mobile.openepay.com/mobilepay/index.do'
_QUERY_GATEWAY = 'http://pay.55555pay.com/search.aspx?orderid={}&parter={}&sign={}'

APP_CONF = {
    '101000171102006': {
        'API_KEY': 'kuangxiangshidaidwc'
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_order_sign(parameter, key):
    s = 'inputCharset={}&receiveUrl={}&version={}&language={}&signType={}&merchantId={}&orderNo={}&orderAmount={}&orderCurrency={}&orderDatetime={}&productName={}&payType={}&key={}'.format(
        parameter['inputCharset'],
        parameter['receiveUrl'],
        parameter['version'],
        parameter['language'],
        parameter['signType'],
        parameter['merchantId'],
        parameter['orderNo'],
        parameter['orderAmount'],
        parameter['orderCurrency'],
        parameter['orderDatetime'],
        parameter['productName'],
        parameter['payType'],
        key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    _LOGGER.info(u'kailianpay origin string: %s, sign:%s', s, sign)
    return sign


def generate_query_sign(parameter, key):
    s = 'orderid={}&parter={}{}'.format(parameter['orderid'], parameter['parter'], key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    _LOGGER.info(u'kailianpay create charge origin string: %s, sign:%s', s, sign)
    return sign


def verify_notify_sign(params, key):
    sign = params.pop('signMsg')
    s = 'merchantId={}&version={}&language={}&signType={}&payType={}&mchtOrderId={}&orderNo={}&orderDatetime={}&orderAmount={}&payDatetime={}&payResult={}&key={}'.format(
        params['merchantId'],
        params['version'],
        params['language'],
        params['signType'],
        params['payType'],
        params['mchtOrderId'],
        params['orderNo'],
        params['orderDatetime'],
        params['orderAmount'],
        params['payDatetime'],
        params['payResult'],
        key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    calculated_sign = m.hexdigest().upper()
    if sign != calculated_sign:
        _LOGGER.info(u'kailianpay notify origin string: %s, calculated_sign: %s, given sign: %s',
                     s, calculated_sign, sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + _GATEWAY + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>document.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    key = _get_api_key(app_id)
    p_dict = OrderedDict((
        ('inputCharset', '1'),
        ('receiveUrl', '{}/pay/api/{}/kailianpay/{}'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('version', 'v1.0'),
        ('language', '1'),
        ('signType', '0'),
        ('merchantId', '101000171102006'),
        ('orderNo', str(pay.id)),
        ('orderAmount', int(pay_amount * 100)),
        ('orderCurrency', '156'),
        ('orderDatetime', datetime.now().strftime("%Y%m%d%H%M%S")),
        ('productName', 'virtual_coin'),
        ('payType', '0'),
    ))
    p_dict['signMsg'] = generate_order_sign(p_dict, key)
    html_text = _build_form(p_dict)
    cache_id = redis_cache.save_html(pay.id, html_text)
    charge_resp = {
        'charge_info': settings.PAY_CACHE_URL + cache_id,
    }
    return charge_resp


def check_notify_sign(request, app_id):
    key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("kailianpay notify data: %s", data)
    verify_notify_sign(data, key)
    pay_id = data['orderNo']
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise ParamError('kailianpay event does not contain valid pay ID')

    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = int(data['payResult'])
    trade_no = data.get('mchtOrderId')
    total_fee = float(data['orderAmount']) / 100

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 1:
        _LOGGER.info('kailianpay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    key = _get_api_key(app_id)
    p_dict = {
        'parter': app_id,
        'orderid': str(pay_id),
    }
    p_dict['sign'] = generate_query_sign(p_dict, key)
    response = requests.get(_QUERY_GATEWAY.format(p_dict['orderid'], p_dict['parter'], p_dict['sign']))
    _LOGGER.info(u'kailianpay create charge: %s', response.text)
    data = json.loads(response.text)
    if response.status_code == 200:
        trade_status = int(data['opstate'])
        total_fee = float(data['ovalue'])
        trade_no = ''
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == 0:
            _LOGGER.info('kailianpay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            res = add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            if res:
                async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('kailianpay data error, status_code: %s', response.status_code)
